﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using app.Models;
using AmuTools;
using System.Data;

namespace app.Api
{
    /*
      查找，返回分页数据
    */
    public class ApiSearch : ApiBase
    {
        public ApiSearch(Controller ctx) : base(ctx) { }

        #region 自定义请求参数
        // 
        #endregion

        public void Do(string action)
        {
            switch (action)
            {
                case "admin_role":
                    CheckPermission(IDENTITY.ADMIN);
                    ResponseJson(GetPageResult<AdminRole>("", G.DB.GetPrimaryKey<AdminRole>()));
                    break;
                case "member_role":
                    ResponseJson(GetPageResult<MemberRole>("", G.DB.GetPrimaryKey<MemberRole>()));
                    break;
                case "admin":
                    ResponseJson(GetPageResult<Admin>("is_must <> 1", G.DB.GetPrimaryKey<Admin>()));
                    break;
                case "member":
                    {
                        string condition = Member.GetSearchSql(
                            GetIntParam(new ReqIntParamOption { Name = "id", Level = REQPARAMLEVEL.FREE }),
                            GetIntParam(new ReqIntParamOption { Name = "role_type", Level = REQPARAMLEVEL.FREE }),
                            GetStringParam(new ReqStringParamOption { Name = "username", Level = REQPARAMLEVEL.FREE }),
                            GetStringParam(new ReqStringParamOption { Name = "area", Level = REQPARAMLEVEL.FREE }),
                            GetStringParam(new ReqStringParamOption { Name = "member_type", Level = REQPARAMLEVEL.FREE }),
                            GetStringParam(new ReqStringParamOption { Name = "title", Level = REQPARAMLEVEL.FREE }),
                            req_begin_time,
                            req_end_time,
                            GetIntParam(new ReqIntParamOption { Name = "status", Level = REQPARAMLEVEL.FREE, DefaultValue = -1 })
                        );
                        // orderby
                        Ob ob = new Ob();
                        ob.Desc("create_time"); // 降序
                        if (req_excel)
                        {
                            DataTable dt = GetSqlResult<Member>(condition, ob.Render()).FirstTable;
                            ResponseExcel(dt, Member.ExcelColumns);
                        }
                        else
                        {
                            ResponseJson(GetPageResult<Member>(condition, ob.Render()), "id,number,username,status,is_ban,enterprise_name,role_type,create_time,area,member_type");
                        }
                        break;
                    }
                case "article":
                    {
                        string m_type = GetStringParam(new ReqStringParamOption { Name = "m_type", Level = REQPARAMLEVEL.FREE, DefaultValue = "" });
                        string p_type = GetStringParam(new ReqStringParamOption { Name = "p_type", Level = REQPARAMLEVEL.FREE, DefaultValue = "" });
                        string a_type = GetStringParam(new ReqStringParamOption { Name = "a_type", Level = REQPARAMLEVEL.FREE, DefaultValue = "" });
                        string search = GetStringParam(new ReqStringParamOption { Name = "search", Level = REQPARAMLEVEL.FREE });


                        Cd cd = new Cd();
                        if (m_type == "") cd.And("m_type=''");
                        else if (m_type == "*") cd.And("m_type <> ''");
                        else cd.And("m_type = '{0}'", m_type);
                        if (p_type != "*" && p_type != "" && !p_type.Equals("0"))
                        {
                            cd.And("p_type ='{0}'", p_type);
                            if (a_type != "*" && a_type != "" && !a_type.Equals("0")) cd.And("a_type ='{0}'", a_type);
                        }
                        if (search != "") cd.And("title like '%{0}%'", search);
                        if (!HasPermission(IDENTITY.ADMIN)) cd.And("status=1");
                        if (req_begin_time != "") cd.And("create_time>='{0}'", req_begin_time);
                        if (req_end_time != "") cd.And("create_time<='{0}'", req_end_time);
                        Ob ob = new Ob();
                        ob.Desc("is_top");
                        ob.Desc("create_time");
                        ResponseJson(GetPageResult<Article>(cd, ob).MapToObj(r => new {
                            r.id,
                            r.title,
                            r.create_time,
                            r.status,
                            r.a_type,
                            r.m_type,
                            r.p_type,
                            r.is_top,
                        }));
                        break;
                    }
                case "special_service":
                    {
                        PlateformService Pservice = G.DB.GetById<PlateformService>(req_id);
                        G.DB.Update<PlateformService>(Pservice);
                        ResponseJson(new ObjectResult { data = Pservice });
                        break;
                    }
                case "plateform_service_abut":
                    {
                        String number = GetStringParam(new ReqStringParamOption { Name = "number", Level = REQPARAMLEVEL.FREE });
                        int id = Int32.Parse(UserCode);
                        Cd cd = new Cd();
                        cd.And("company_id = '{0}'", id);
                        if (number != "")
                        {
                            cd.And("number like '%{0}%'", number);
                        }
                        Ob ob = new Ob();
                        ob.Desc("create_time");
                        ResponseJson(GetPageResult<PlateformServiceAbutment>(cd, ob));
                        break;
                    }
                case "plateform_service_abutment":
                    {
                        int status = GetIntParam(new ReqIntParamOption { Name = "status" });
                        string title = GetStringParam(new ReqStringParamOption { Name = "title", Level = REQPARAMLEVEL.FREE });
                        Cd cd = new Cd();
                        if (status != 0)
                        {
                            cd.And("status = {0}", status);
                        }
                        if(title != "")
                        {
                            cd.And("");
                        }
                        Ob ob = new Ob();
                        ob.Desc("create_time");
                        ResponseJson(GetPageResult<PlateformServiceAbutment>(cd, ob));
                        break;
                    }
                case "plateform_service":
                    {
                        string title = GetStringParam(new ReqStringParamOption { Name = "title", Level = REQPARAMLEVEL.FREE });
                        string number = GetStringParam(new ReqStringParamOption { Name = "number", Level = REQPARAMLEVEL.FREE });
                        Cd cd = new Cd();
                        if (title != "")
                        {
                            cd.And("title like '%{0}%'", title);
                        }
                        if (number != "")
                        {
                            cd.And("number like'%{0}%'", number);
                        }
                        cd.And("status = 2");
                        cd.And("isvisiable = 1");
                        Ob ob = new Ob();
                        ob.Desc("create_time");
                        PageResult<PlateformService> result = GetPageResult<PlateformService>(cd.Render(), ob.Render());
                        ResponseJson(
                            GetPageResult<PlateformService>(cd.Render(), ob.Render())
                            .MapToObj(r => new {
                                id = r.id,
                                title = r.title,
                                content = r.content.Length > 20 ? r.content.Substring(20) + "..." : r.content,
                                create_time = r.create_time,
                            })
                        );
                        break;
                    }
                case "service_item":
                    {
                        string service_type = GetStringParam(new ReqStringParamOption { Name = "service_type", Level = REQPARAMLEVEL.FREE, DefaultValue = "0" });
                        //string service_area = GetStringParam(new ReqStringParamOption { Name = "area" });
                        string search = GetStringParam(new ReqStringParamOption { Name = "search", Level = REQPARAMLEVEL.FREE });
                        string search_number = GetStringParam(new ReqStringParamOption { Name = "search_number", Level = REQPARAMLEVEL.FREE });
                        string m_type = GetStringParam(new ReqStringParamOption { Name = "m_type", Level = REQPARAMLEVEL.FREE, DefaultValue = "0" });
                        // condition
                        Cd cd = new Cd();
                        if(m_type != "0") cd.And("m_type = '{0}'", m_type);
                        if (!"0".Equals(service_type)) cd.And("service_type = '{0}' ", service_type);
                        if (!"".Equals(search)) cd.And("title like '%{0}%'", search);
                        if (!"".Equals(search_number)) cd.And("number like '%{0}%'", search_number);
                        cd.And("status = 2");
                        if (req_begin_time != "") cd.And("create_time>='{0}'", req_begin_time);
                        if (req_end_time != "") cd.And("create_time<='{0}'", req_end_time);
                        //if (!"".Equals(service_area)) cd.And("service_address like '{0}%'", service_area);
                        // orderby
                        Ob ob = new Ob();
                        ob.Desc("create_time"); // 降序
                        ResponseJson(
                            GetPageResult<ServiceItem>(cd.Render(), ob.Render())
                            .MapToObj(r => new {
                                id = r.id,
                                r.number,
                                title = r.title,
                                service_content = r.service_content.Length > 20 ? r.service_content.Substring(20) + "..." : r.service_content,
                                service_people = r.service_people,
                                service_master = r.service_master,
                                create_time = r.create_time,
                                r.m_type
                            })
                        );
                        break;
                    }
                case "demand_item":
                    {
                        string demand_type = GetStringParam(new ReqStringParamOption { Name = "demand_type", Level = REQPARAMLEVEL.FREE, DefaultValue = "0" });
                        string demand_area = GetStringParam(new ReqStringParamOption { Name = "area", Level = REQPARAMLEVEL.FREE });
                        string search = GetStringParam(new ReqStringParamOption { Name = "search", Level = REQPARAMLEVEL.FREE });
                        string search_number = GetStringParam(new ReqStringParamOption { Name = "search_number" , Level = REQPARAMLEVEL.FREE});
                        string m_type = GetStringParam(new ReqStringParamOption { Name = "m_type", Level = REQPARAMLEVEL.FREE, DefaultValue = "0" });
                        // condition
                        Cd cd = new Cd();
                        if (m_type != "0") cd.And("m_type = '{0}'", m_type);
                        if (!"".Equals(search_number)) cd.And("number like '%{0}%'", search_number);
                        if (!"0".Equals(demand_type)) cd.And("demand_type = '{0}' ", demand_type);
                        if (!"".Equals(search)) cd.And("title like '%{0}%'", search);
                        cd.And("status = 2");
                        // 如果当前用户不是服务机构或者当前用户是未通过审核的服务机构，只显示公开的需求项目
                        if((ROLE_TYPES)UserRole != ROLE_TYPES.SERVICE || G.DB.GetById<Member>(UserCode).status != 2) cd.And("safety_grade=0");
                        cd.And("demand_area like '{0}%'", demand_area);
                        if (req_begin_time != "") cd.And("create_time>='{0}'", req_begin_time);
                        if (req_end_time != "") cd.And("create_time<='{0}'", req_end_time);                      
                        // orderby
                        Ob ob = new Ob();
                        ob.Desc("create_time"); // 降序
                        ResponseJson(
                            GetPageResult<DemandItem>(cd.Render(), ob.Render())
                            .MapToObj(r => new {
                                id = r.id,
                                r.number,
                                title = r.title,
                                demand_content = r.demand_content.Length > 20 ? r.demand_content.Substring(20) + "..." : r.demand_content,
                                demand_industry = r.demand_industry,
                                demand_master = r.demand_master,
                                create_time = r.create_time,
                                r.m_type,
                                r.demand_tele
                            })
                        );
                        break;
                    }
                case "abutment_item":
                    {
                        int abutment_status = GetIntParam(new ReqIntParamOption { Name = "abutment_status", Level = REQPARAMLEVEL.FREE });
                        string sponsor = GetStringParam(new ReqStringParamOption { Name = "sponsor" });
                        string search = GetStringParam(new ReqStringParamOption { Name = "search" });
                        string search_number = GetStringParam(new ReqStringParamOption { Name = "search_number" });
                        string status_str = "";
                        // condition
                        Cd cd = new Cd();
                        switch (abutment_status)
                        {
                            //全部
                            case 0: status_str = string.Format("(demand_status >= 1 or service_status >= 1)"); break;
                            //正在约谈
                            case 1: status_str = string.Format("(demand_status = {0} and service_status = {1}) or (service_status = {0} and demand_status = {1})or (service_status = {0} and demand_status = {0})", (int)ABUTMENT_STATUS.INTERVIEW, (int)ABUTMENT_STATUS.AGREE);break;
                            //正在合作
                            case 2: status_str = string.Format("(demand_status = {0} and service_status = {1}) or (service_status = {0} and demand_status = {1}) or (service_status = {0} and demand_status = {0})", (int)ABUTMENT_STATUS.AGREE, (int)ABUTMENT_STATUS.FINISH); break;
                            //合作完成
                            case 3: status_str = string.Format("(demand_status = {0} and service_status = {0})", (int)ABUTMENT_STATUS.FINISH); break;
                            //取消合作
                            case 4: status_str = string.Format("(demand_status = {0} or service_status = {0}) and demand_status <> {1} and service_status <> {1}", (int)ABUTMENT_STATUS.CANCEL, (int)ABUTMENT_STATUS.NONE); break;
                        }
                        cd.And(status_str);
                        if (!"".Equals(search)) cd.And("title like '%{0}%'", search);
                        if (!"".Equals(search_number)) cd.And("number like '%{0}%'", search_number);
                        //if (!"".Equals(search)) cd.And("description like '%{0}%'", search);                      
                        if (!"0".Equals(sponsor)) cd.And("sponsor = '{0}' ", sponsor);
                        if (req_begin_time != "") cd.And("create_time>='{0}'", req_begin_time);
                        if (req_end_time != "") cd.And("create_time<='{0}'", req_end_time);
                        // orderby
                        Ob ob = new Ob();
                        ob.Desc("create_time"); // 降序
                        ResponseJson(GetPageResult<Abutment>(cd.Render(), ob.Render()).MapToObj(r => new {
                            r.id,
                            r.number,
                            r.title,
                            r.description,
                            r.sponsor,
                            r.demand_enterprise,
                            r.demand_name,
                            r.demand_status,
                            r.service_enterprise,
                            r.service_name,
                            r.service_status,
                            r.create_time
                        }));
                        break;
                    }
                case "log":
                    {
                        // 筛选条件：角色类型role_type，操作类型operation_type，开始时间begin_time，结束时间end_time，用户id
                        Cd cd = new Cd();
                        Ob ob = new Ob();
                        if (req_operation_type != 0) cd.And("operation={0}", req_operation_type);
                        string id = GetStringParam(new ReqStringParamOption { Name = "id", Level = REQPARAMLEVEL.FREE });
                        if (id != "") cd.And("user_id={0}", id);
                        if (req_begin_time != "")
                        {
                            cd.And("create_time>='{0}'", req_begin_time);
                        }
                        if (req_end_time != "")
                        {
                            cd.And("create_time<='{0}'", req_end_time);
                        }
                        if (req_role_type == 2)
                        {
                            cd.And("role_type={0}", req_role_type);

                        }
                        else if (req_role_type != 0)
                        {
                            cd.And("role_type={0}", req_role_type);

                        }
                        else
                        {
                            cd.And("role_type != {0}", 2);
                        }
                        ob.Desc("create_time");
                        ResponseJson(GetPageResult<Log>(cd.Render(), ob.Render()));
                        break;

                    }
                case "ip_location":
                    {
                        string sql = string.Format("(select ip_location ,COUNT(*) as times from t_log where role_type=2 group by ip_location) as temp");
                        //Dictionary<string, object> ip_locations = G.DB.Get(sql).FirstTable;
                        ResponseJson(GetPageResult(sql, "", "times desc"));
                        break;
                    }
                case "admin_login":
                    {
                        string sql = string.Format("(select username, COUNT(*) as times from t_log where role_type=2 group by username) as temp");
                        ResponseJson(GetPageResult(sql, "", "times desc"));
                        break;
                    }
                case "ip_location_user":
                    {
                        string sql = string.Format("(select ip_location ,COUNT(*) as times from t_log where role_type<>2 group by ip_location) as temp");
                        ResponseJson(GetPageResult(sql, "", "times desc"));
                        break;
                    }
                case "user_login_times":
                    {
                        string sql = string.Format("(select username, COUNT(*) as times from t_log where role_type <> 2 group by username) as temp");
                        ResponseJson(GetPageResult(sql, "", "times desc"));
                        break;
                    }
                case "help_document":
                    {
                        string type = GetStringParam(new ReqStringParamOption { Name = "type", Level = REQPARAMLEVEL.FREE, DefaultValue = "*" });
                        Cd cd = new Cd();
                        string search = GetStringParam(new ReqStringParamOption { Name = "search", Level = REQPARAMLEVEL.FREE });
                        if (search != "") cd.And("title like '%{0}%'", search);
                        if (type != "*") cd.And("hd_type = '{0}'", type);
                        if (req_begin_time != "") cd.And("create_time>='{0}'", req_begin_time);
                        if (req_end_time != "") cd.And("create_time<='{0}'", req_end_time);
                        if(UserIdentity != IDENTITY.ADMIN) cd.And("status = 1");
                        ResponseJson(GetPageResult<HelpDocument>(cd.Render(), G.DB.GetPrimaryKey<HelpDocument>()));
                        break;
                    }
                case "message":
                    {
                        string search = GetStringParam(new ReqStringParamOption { Name = "search", Level = REQPARAMLEVEL.FREE });
                        int m_type = GetIntParam(new ReqIntParamOption { Name = "m_type", Level = REQPARAMLEVEL.FREE, DefaultValue = -1 });
                        int status = GetIntParam(new ReqIntParamOption { Name = "status", Level = REQPARAMLEVEL.FREE, DefaultValue = -1 });
                        Cd cd = new Cd();
                        if (search != "") cd.And("title like '%{0}%'", search);
                        if (m_type != -1) cd.And("m_type = {0}", m_type);
                        if (status != -1) cd.And("status = {0}", status);
                        Ob ob = new Ob();
                        ob.Desc("create_time");
                        ResponseJson(GetPageResult<MemberMessage>(cd, ob));
                        break;
                    }
                default: break;
            }
        }
    }
}